package org.example.queue.delayQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

/**
 * 无界延迟阻塞队列
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2021/8/28 14:52
 */
public class OrderDelayedTest {
    private static final Logger LOG = LoggerFactory.getLogger(OrderDelayedTest.class);

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("00000001");
        list.add("00000002");
        list.add("00000003");
        list.add("00000004");
        list.add("00000005");
        DelayQueue<OrderDelayed> queue = new DelayQueue<>();

        // 1、指定子线程从队列中获取元素，一个线程获取了元素后，其它线程无法再获取.
        //take():获取并移除队列的超时元素，如果没有则阻塞当前线程，直到有元素满足超时条件，返回结果
        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true) {
                            OrderDelayed orderDelayed = queue.take();
                            LOG.warn("订单已超时：" + orderDelayed.toString());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        // 2、指定子线程往队列中存储元素
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0, size = list.size(); i < size; i++) {
                        TimeUnit.SECONDS.sleep(1);
                        int nextInt = 3 + SecureRandom.getInstanceStrong().nextInt(10);
                        OrderDelayed orderDelayed = new OrderDelayed(list.get(i), "土鸡蛋订购", nextInt, TimeUnit.SECONDS);
                        queue.put(orderDelayed);
                        LOG.info("订单已提交：" + orderDelayed.toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        LOG.info("我是主线程.");
        new Scanner(System.in).next();
    }
}